package com.hs.telepass.controller;

import android.content.Context;

import com.baidu.android.pushservice.PushManager;
import com.hs.telepass.controller.task.*;
import com.hs.telepass.manager.PreferencesManager;
import com.hs.telepass.model.json.Requst.UpdatePasswordReqJson;
import com.hs.telepass.model.json.Requst.VerifyPasswordReqJson;
import com.hs.telepass.utils.JsonUtil;
import com.hs.telepass.utils.security.AESEnc;
import com.hs.telepass.utils.security.Base64Utils;
import com.hs.telepass.utils.security.Sha1Util;
import org.apache.commons.codec.digest.DigestUtils;

import java.math.BigInteger;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;

public class TaskController {
    public static final int EVENT_TASK_BEGIN = 0;
    public static final int EVENT_TASK_PROGRESS = 1;
    public static final int EVENT_TASK_SUCCEED = 2;
    public static final int EVENT_TASK_FAILED = 3;
    public static final int EVENT_TASK_ERROR = 4;
    public static final int EVENT_TASK_END = 5;

    public static final int ERROR_CODE_TIMEOUT = 1;
    public static final int ERROR_CODE_NO_NET = 2;
    public static final int ERROR_CODE_SERVER_NOT_FOUND = 3;
    public static final int ERROR_CODE_NO_UNKNOWN = 4;


    public static final String EXTRA_EVENT = "EXTRA_EVENT";

    public static final String EXTRA_RESPONSE = "EXTRA_RESPONSE";

    private final Object LOCK = new Object();

    public static TaskController instance;

    public static TaskController getInstance() {
        if (null == instance)
            instance = new TaskController();
        return instance;
    }

    public TaskController() {
    }

    public int getErrorCodeByException(Exception e) {
        if (e instanceof SocketException) {
            return ERROR_CODE_SERVER_NOT_FOUND;
        } else if (e instanceof SocketTimeoutException) {
            return ERROR_CODE_TIMEOUT;
        } else {
            return ERROR_CODE_NO_UNKNOWN;
        }
    }

    public void fetchPublicKey(Context context, String enc_sessionid, String uuid) throws Exception {
        synchronized (LOCK){
            FetchPubkeyTask task = new FetchPubkeyTask(context, enc_sessionid, uuid);
            TaskQueue.enqueue(context, task);
        }
    }

    public void updateSession(Context context, String sessionId, String aesBase64) throws Exception {
        synchronized (LOCK){
            UpdateSessionTask task = new UpdateSessionTask(sessionId, aesBase64);
            TaskQueue.enqueue(context, task);
        }
    }

    public void startSingouSession(Context context,String runtime_key, String reqJson, boolean isFromUpdate) throws Exception {
        synchronized (LOCK){
            StartSingouSessionTask task = new StartSingouSessionTask(runtime_key, reqJson, isFromUpdate);
            TaskQueue.enqueue(context, task);
        }
    }

    public void initSingouAuth(Context context,String sid, String req) throws Exception {
        synchronized (LOCK){
            InitSingouAuthTask task = new InitSingouAuthTask(sid, req);
            TaskQueue.enqueue(context, task);
        }
    }

    public void sendAuth(Context context, String sid, String req, String encrypted_payload) throws Exception {
        synchronized (LOCK){
            SendAuthTask task = new SendAuthTask(sid, req, encrypted_payload);
            TaskQueue.enqueue(context, task);
        }
    }

    public void getAuth(Context context, String sid, String req) throws Exception {
        synchronized (LOCK){
            GetAuthStatusTask task = new GetAuthStatusTask(sid, req);
            TaskQueue.enqueue(context, task);
        }
    }

    /**
     * 获得该二维码对应的信息, logo, title等
     * */
    public void getRepositoryProfile(Context context, String serviceId, String serviceName) throws Exception {
        synchronized (LOCK){
            GetProfileInfoTask task = new GetProfileInfoTask(serviceId, serviceName);
            TaskQueue.enqueue(context, task);
        }
    }

    /**
     * 初始化singou密码
     * */
    public void verifyPassword(String sid, Context context, String password, String runtime_key) throws Exception {
        synchronized (LOCK){
          /*  byte[] data = DigestUtils.sha1(password);
            String shaPassword = String.format("%0" + (data.length * 2) + "X", new BigInteger(1, data)).toLowerCase();*/
            String shaPassword = Sha1Util.sha1(password);
            VerifyPasswordReqJson jsonObj = new VerifyPasswordReqJson();
            jsonObj.setPassword(shaPassword);
            String reqJson = JsonUtil.toJson(jsonObj);
            AESEnc aes = new AESEnc(runtime_key.getBytes());
            String reqData = Base64Utils.encode(aes.encrypt(reqJson.getBytes()));
            //对特殊字符进行转义
            reqData = URLEncoder.encode(reqData);
            VerifyPasswordTask verifyPasswordTask = new VerifyPasswordTask(sid, reqData, runtime_key);
            TaskQueue.enqueue(context, verifyPasswordTask);
        }
    }

    /**
     * 修改singou密码
     * */
    public void updatePassword(Context context, String sid, String newPassword, String runtime_key) throws Exception {
        synchronized (LOCK){
            UpdatePasswordReqJson updatePasswordReqJson = new UpdatePasswordReqJson();
            String oldPassword = PreferencesManager.getInstance().getPasswordKey();
            oldPassword =Sha1Util.sha1(oldPassword);
            newPassword =Sha1Util.sha1(newPassword);
            updatePasswordReqJson.setPassword(oldPassword);
            updatePasswordReqJson.setNpassword(newPassword);

            String jsonStr = JsonUtil.toJson(updatePasswordReqJson);
            AESEnc aes = new AESEnc(runtime_key.getBytes());
            String req = Base64Utils.encode(aes.encrypt(jsonStr.getBytes()));
            //对特殊字符进行转义
            req = URLEncoder.encode(req);
            UpdatePasswordTask task = new UpdatePasswordTask(sid, req, runtime_key);
            TaskQueue.enqueue(context, task);
        }
    }

    /**
     * 获取社团信息
     * */
    public void getOrgInfo(Context context, String meetingId){
        synchronized (LOCK){
            GetOrgInfoTask task = new GetOrgInfoTask(meetingId);
            TaskQueue.enqueue(context, task);
        }
    }

    /**
     * 绑定设备token
     * */
    public void setDeviceToken(Context context, int storeId, String lastFiveNum, String deviceModel){
        synchronized (LOCK){
            String token = PreferencesManager.getInstance().getToken();
            SetDeviceTokenTask task = new SetDeviceTokenTask(storeId, lastFiveNum, deviceModel, token);
            TaskQueue.enqueue(context, task);
        }
    }
}